import Taro from '@tarojs/taro';

import { Command } from '../constant';
import { Dispatch } from 'typings';
import { getActionProxy } from '@/redux/action-util';
import * as reduxStore from '@/redux/store';
import packageAddPickupCourierDMain from '../reducers/main';
import { addressInfo } from '@/utils/location/area/area';
import Action from './action';

import api from 'api';

export default (dispatch?: Dispatch) => {
  const actions = {
    action: getActionProxy<typeof Action>(Action)(dispatch),

    /**
     * 初始化数据
     */
    async init(id, deliveryAddressId) {


      // 获取小区名称 --+快递站点
      const community: any = await api.customerDrawCashController.communityList();
      // const community = [{
      //   communityId: 1,
      //   communityName: 1,
      //   courierStationVOS: [{
      //     courierStationId: 2,
      //     courierStationName: '2'
      //   }]

      // }]

      actions.action._pointInit()
      let addressSelect = Taro.getStorageSync('Select delivery address')
      let { user: { phone, wxOpenId }, shopUser } = Taro.getStorageSync('b2b-wechat@login')
      const { accountBalanceTotal } = await api.customerDrawCashController.statistics();
      const { code } = await api.customerDrawCashController.isPayPwdValid();
      let isPayPwdValid = true
      if (code === 'K-010206') {
        // 未设置支付密码
        isPayPwdValid = false
      }
      let { context: { customerId } } = JSON.parse(shopUser)

      // 获取计价规则
      const rule = await api.customerDrawCashController.deliveryfee();

      dispatch({
        type: Command.init,
        payload: {
          main: {
            isLoading: true,
            community,
            addressSelect,
            phone,
            accountBalanceTotal,
            isPayPwdValid,
            customerId,
            openid: wxOpenId,
            rule
          },
        },
      });

      if (id) {
        // 存在id则获取订单讯息回显
        let result: any = await api.escortTradeController.findEscorttradeDetail(id);
        if (result?.code === 'K-000000') {
          let { context: { communityId, communityName, communityAddress, courierStationId, courierStationName } } = result

          let communityExists = false;
          let stationExists = false;
          let courierStation;
          for (const communityItem of community) {
            if (communityItem.communityId === communityId) {
              communityExists = true;
              courierStation = communityItem.courierStationVOS
              for (const station of communityItem.courierStationVOS) {
                if (station.courierStationId === courierStationId) {
                  stationExists = true;
                  break; // 如果找到了匹配，就不需要继续搜索
                }
              }
              break;
            }
          }
          if (communityExists) {
            actions.action.commonChange('main.communityId', communityId)
            actions.action.commonChange('main.communityName', communityName)
            actions.action.commonChange('main.communityAddress', communityAddress)
            actions.action.commonChange('main.courierStation', courierStation)
          }

          if (stationExists) {
            actions.action.commonChange('main.courierStationId', courierStationId)
            actions.action.commonChange('main.courierStationName', courierStationName)
          }
        }
        // 获取并存储已选地址讯息
        result = await api.escortTradeController.getAddressInfo(deliveryAddressId);
        if (result?.code === 'K-000000') {
          let { context: { provinceId, cityId, areaId, streetId, deliveryAddress, } } = result
          let addressInfoStr;
          if (streetId != -1) {
            addressInfoStr = await addressInfo(provinceId, cityId, areaId, streetId);
          } else {
            addressInfoStr = await addressInfo(provinceId, cityId, areaId);
          }
          addressInfoStr += deliveryAddress ? deliveryAddress : '';
          // addressInfo
          // deliveryAddressId
          Taro.setStorageSync('Select delivery address', { addressInfo: addressInfoStr, deliveryAddressId })
          actions.action.commonChange('main.addressSelect', JSON.parse(JSON.stringify({ addressInfo: addressInfoStr, deliveryAddressId })))
        }
      }
    },

    /**
     * 重置
     */
    async clean() {
      //@ts-ignore
      __TARO_ENV !== 'h5' && (await actions.unloadReducer());
      dispatch({ type: Command.clean });
    },

    /**
     * 动态添加注入reducer
     */
    async loadReducer() {
      reduxStore.registerReducer({
        packageAddPickupCourierDMain,
      });
    },

    /**
     * 卸载reducer
     */
    async unloadReducer() {
      if (reduxStore.deregister) {
        reduxStore.deregister(['packageAddPickupCourierDMain']);
      } else {
        console.error('请在redux/store中实现deregister逻辑. ');
      }
    },
  };

  return { actions };
};
